package com.ming.common.dynamic.spring.dynamic;

import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;
import com.sun.tools.javac.util.ListBuffer;

import java.io.File;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
import java.util.Iterator;

/**
 * Java 文件管理器
 *
 * @author moon
 * @date 2023-08-10 9:53
 * @since 1.8
 */
public class SpringJavaFileManager extends JavacFileManager {

    /**
     *
     * @param context
     * @param b
     * @param charset
     */
    public SpringJavaFileManager(Context context, boolean b, Charset charset) {
        super(context, b, charset);
    }

    /**
     * 重写类加载器
     * @param location a location
     * @return
     */
    @Override
    public ClassLoader getClassLoader(Location location) {
        nullCheck(location);
        Iterable var2 = this.getLocation(location);
        if (var2 == null) {
            return null;
        } else {
            ListBuffer var3 = new ListBuffer();
            Iterator var4 = var2.iterator();
            while (var4.hasNext()) {
                File var5 = (File) var4.next();
                try {
                    var3.append(var5.toURI().toURL());
                } catch (MalformedURLException var7) {
                    throw new AssertionError(var7);
                }
            }
            return this.getClassLoader((URL[]) var3.toArray(new URL[var3.size()]));
        }
    }

    /**
     * 获取 LaunchedURLClassLoader 加载器
     *
     * @param var1
     * @return
     */
    @Override
    protected ClassLoader getClassLoader(URL[] var1) {
        ClassLoader var2 = this.getClass().getClassLoader();
        try {
            Class loaderClass = Class.forName("org.springframework.boot.loader.LaunchedURLClassLoader");
            Class[] var4 = new Class[]{URL[].class, ClassLoader.class};
            Constructor var5 = loaderClass.getConstructor(var4);
            return (ClassLoader) var5.newInstance(var1, var2);
        } catch (Throwable var6) {
        }
        return new URLClassLoader(var1, var2);
    }

}
